var arrNFs = localStorage.getItem("nfs");

arrNFs = JSON.parse(arrNFs);
if (arrNFs === null) arrNFs = [];

$(function(){
	FillValues();
	
	$("#btn_import").bind("click", function(){
		ImportValues();		
		FillValues();
		SumValues();
	});
	
	$("#btn_clear").bind("click", function(){
		$("#txt_cvs").val("");
	});
	
	$("#btn_reset").bind("click", function(){
		localStorage.clear();
		arrNFs = [];
		FillValues();
	});
});

function ImportValues(){
	var arrList = null;
	arrList = $("#txt_cvs").val().split(/\r\n|\r|\n/g);
	
	for(var i in arrList){
		var arrItens = null;
		arrItens = arrList[i].split(":::");
	
		var nf = {
				cnpj : arrItens[0],
				emitente : arrItens[1], 
				nro : arrItens[2],
				emissao : arrItens[3],
				valor : arrItens[4],
				registro : arrItens[5],
				creditos : arrItens[6],
				situacao : arrItens[7],
		};
	 
		arrNFs.push(nf);
	}
	
	localStorage.setItem("nfs", JSON.stringify(arrNFs));	
	alert("Imported");
}

function FillValues(){
	$("#tbl_values tbody").html("");
	var rows = "";

	if (arrNFs === null || arrNFs.length === 0){
		$("#tbl_values tbody").append("<tr><td colspan='9'>Nenhum valor encontrado.</td></tr>");
	}else{
		for(var i in arrNFs){
			var nf = arrNFs[i];
			
			rows += "<tr>";
			rows += "<td>" + i + "</td>";
			rows += "<td>" + nf.cnpj + "</td>";
			rows += "<td>" + nf.emitente + "</td>";
			rows += "<td align='right'>" + nf.nro + "</td>";
			rows += "<td align='right'>" + nf.emissao + "</td>";
			rows += "<td align='right'>" + nf.valor + "</td>";
			rows += "<td align='right'>" + nf.registro + "</td>";
			rows += "<td align='right'>" + nf.creditos + "</td>";
			
			if(nf.situacao === "LIBERADO")
				rows += "<td align='center'><span class='label label-info'>" + nf.situacao + "</span></td>";
			else if(nf.situacao === "CALCULADO")
				rows += "<td align='center'><span class='label label-success'>" + nf.situacao + "</span></td>";
			else
				rows += "<td align='center'><span class='label label-warning'>" + nf.situacao + "</span></td>";
			
				rows += "</tr>";
		};
		
		$("#tbl_values tbody").append(rows);
	}
}

function SumValues(){
	$("#tbl_sum tbody").html("");
	var rows = "";

	if (arrNFs === null || arrNFs.length === 0)
		$("#tbl_sum tbody").append("<tr><td colspan='9'>Nenhum valor encontrado.</td></tr>");
}
